﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.SessionState;

namespace Web.Resource
{
    /// <summary>
    /// 资源操作权限处理
    /// </summary>
    public class ResHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 类型实例是否重复使用
        /// </summary>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="context">上下文</param>
        public void ProcessRequest(HttpContext context)
        {
            var url = context.Request.Url.AbsolutePath;
            var fileType = url.Match(@"\w*$").ToLower();


            // 是图片就返回图片的流
            if (fileType.IsMatch(@"png|jpg|jpeg|ico|gif|bmp"))
            {
                this.ResponseRes(context, url);
                return;
            }           

            context.Response.Redirect("/other/error/");
        }

        /// <summary>
        /// 以流的形式输出资源文件
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="url">请求的url</param>
        private void ResponseRes(HttpContext context, string url)
        {
            var res = ResManage.Parse(url);
            if (res.Exist == true)
            {
                using (var stream = new FileStream(res.FullFileName, FileMode.Open, FileAccess.Read))
                {
                    var buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    context.Response.BinaryWrite(buffer);
                }
            }
        }
    }
}